package com.yc.web;

import com.yc.services.AlipayService;
import com.yc.services.OrdersService;
import com.yc.web.controller.model.ResponseResult;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.java.Log;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/payment")
@RequiredArgsConstructor
@Log
public class PaymentController {

    private final AlipayService alipayService;
    private final OrdersService ordersService;

    @GetMapping("/qr-code")
    public ResponseEntity<ResponseResult> getQrCode(
            @RequestParam String ordersId,
            @RequestParam String totalAmount,
            @RequestParam String subject) {

        // 验证订单ID格式
        if (ordersId == null || ordersId.length() < 6) {
            return ResponseEntity.badRequest()
                    .body(ResponseResult.error("订单号格式不正确"));
        }

        try {
            // 验证金额
            new BigDecimal(totalAmount);

            String qrCodeUrl = alipayService.createQrCode(ordersId, totalAmount, subject);

            // 构造返回数据
            Map<String, Object> data = new HashMap<>();
            data.put("qrCodeUrl", qrCodeUrl);
            data.put("outTradeNo", ordersId);
            data.put("amount", totalAmount);
            data.put("subject", subject);
            data.put("isSandbox", true);  // 标记为沙箱环境

            return ResponseEntity.ok()
                    .body(ResponseResult.ok("沙箱测试二维码生成成功").setData(data));
        } catch (NumberFormatException e) {
            return ResponseEntity.badRequest()
                    .body(ResponseResult.error("金额格式不正确，必须为数字"));
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest()
                    .body(ResponseResult.error(e.getMessage()));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ResponseResult.error("二维码生成失败: " + e.getMessage()));
        }
    }


    @GetMapping("/status")
    public ResponseEntity<ResponseResult> checkPaymentStatus(
            @RequestParam String orderId) {

        try {
            // 验证订单ID格式
            if (orderId == null || orderId.length() < 6) {
                return ResponseEntity.badRequest()
                        .body(ResponseResult.error("订单号格式不正确"));
            }

            // 检查订单支付状态
            boolean isPaid = ordersService.checkOrderPaid(Long.parseLong(orderId));

            // 构造返回数据
            Map<String, Object> data = new HashMap<>();
            data.put("paid", isPaid);
            data.put("orderId", orderId);

            return ResponseEntity.ok()
                    .body(ResponseResult.ok("查询成功").setData(data));

        } catch (NumberFormatException e) {
            return ResponseEntity.badRequest()
                    .body(ResponseResult.error("订单ID必须为数字"));
        } catch (RuntimeException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ResponseResult.error("查询支付状态失败: " + e.getMessage()));
        }
    }

    /**
     * 支付宝异步通知回调
     */
    @PostMapping("/notify")
    public String alipayNotify(HttpServletRequest request) {
        try {
            Map<String, String> params = convertRequestParamsToMap(request);

            // 验证签名
            if (!alipayService.verifySignature(params)) {
                log.warning("支付宝回调签名验证失败: " + params);
                return "failure";
            }

            String outTradeNo = params.get("out_trade_no");
            String tradeStatus = params.get("trade_status");

            log.info("收到支付宝回调, 订单号: " + outTradeNo + ", 状态: " + tradeStatus);

            // 处理支付成功逻辑
            if ("TRADE_SUCCESS".equals(tradeStatus) || "TRADE_FINISHED".equals(tradeStatus)) {
                // 更新订单状态为已支付
                boolean updated = ordersService.updateOrderStatus(Long.parseLong(outTradeNo), 2);

                if (!updated) {
                    log.warning("订单状态更新失败, 订单号: " + outTradeNo);
                    return "failure";
                }

                log.info("订单支付状态更新成功, 订单号: " + outTradeNo);
            }

            return "success";
        } catch (Exception e) {
            log.severe("处理支付宝回调失败: " + e.getMessage());
            return "failure";
        }
    }

    private Map<String, String> convertRequestParamsToMap(HttpServletRequest request) {
        Map<String, String> params = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();

        for (String name : requestParams.keySet()) {
            String[] values = requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            params.put(name, valueStr);
        }
        return params;
    }


}